import json
from app.models import Department
from django.views import View
from django.http import JsonResponse


class Departments(View):
    def post(self, req):
        d = json.loads(req.body)
        Department.objects.create(name=d["name"])
        return JsonResponse({"code": 200, "message": "添加成功"})

    def get(self, req):
        da = list(Department.objects.all().values())
        return JsonResponse({"code": 200, "data": da, "message": "获取成功"})

    def put(self, req):
        d = json.loads(req.body)
        Department.objects.filter(id=d["id"]).update(name=d["name"])
        return JsonResponse({"code": 200, "message": "修改成功"})

    def delete(self, req):
        d = json.loads(req.body)
        Department.objects.filter(id=d["id"]).delete()
        return JsonResponse({"code": 200, "message": "删除成功"})
